<?php

namespace backend\controllers;

use Yii;
use backend\models\PayTradeRebate;
use backend\models\PayTradeRebateSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\models\PayRebateUsertake;
use frontend\models\SendSms;
use common\models\UserInfo;
use MakemoneyApi;
use backend\models\MakemoneyLog;
include_once "../../vendor/alipay/pagepay/makemoneyApi.php";
/**
 * IntegralController implements the CRUD actions for PayTradeRebate model.
 */
class RebatesController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }
    public function actionCount() {
        $id = Yii::$app->request->post('id');
        $add = PayTradeRebate::find()->where(['uid'=>$id])->sum('rebate_money');
        $minus = PayRebateUsertake::find()->where(['uid'=>$id])->sum('take_money');
        if (empty($add)){
            $add =0;
        }
        if (empty($minus)){
            $minus =0;
        }
        $count = $add - $minus;
        echo json_encode($count);
    }
    public function actionTel() {
        $tel = Yii::$app->request->post('id');
        $id = UserInfo::findOne(['tel'=>$tel])->id;
        $add = PayTradeRebate::find()->where(['uid'=>$id])->sum('rebate_money');
        $minus = PayRebateUsertake::find()->where(['uid'=>$id])->sum('take_money');
        if (empty($add)){
            $add =0;
        }
        if (empty($minus)){
            $minus =0;
        }
        $count = $add - $minus;
        echo json_encode($count);
    }

    /**
     * Lists all PayTradeRebate models.. 
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new PayTradeRebateSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * 返点待审核 列表
     */
    public function actionAuditIndex(){
        $searchModel = new PayTradeRebateSearch();
        $dataProvider = $searchModel->auditSearch(Yii::$app->request->queryParams);
        return $this->render('audit_index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * 审核返点
     */
    public function actionAudit($id){
        $model = PayRebateUsertake::find()
        ->select(['uid','pay_rebate_usertake.id','pay_rebate_usertake.id','tel','take_money','take_time','apply_time','memo'])
        ->join('LEFT JOIN', 'user_info', 'user_info.id = pay_rebate_usertake.uid')
        ->where(['=','pay_rebate_usertake.id',$id])->one();
        if ($model->load(Yii::$app->request->post()) ) {
            $state=intval($model->state);
            if($state==3){
                $tel=$model->tel; 
                $sms=new SendSms();
                $str="您好，您的提现被驳回，请同客服确认后重新提现!";
                if($sms->send_mobile_SMS($tel,$str))
                {
                    echo "验证码发送成功";
                }
                else
                {
                    echo "验证码发送失败，请重试。";
                }
                $model->state=3;
                $model->err_time=time();
                $model->save();
                return $this->redirect(['audit-index']);
            }
            $model->ok_time=time();
            $model->audit_uid=Yii::$app->user->identity->id;
            if($model->save()){
                return $this->redirect(['nview', 'id' => $model->id]);
            }else{
                return $this->redirect(['audit-index']);
            }
        } else {
            return $this->render('nupdate', [
                'model' => $model,
            ]);
        }
    }
    /**
     * 返点待打款 列表
     */
    public function actionMakeMoney(){
        $searchModel = new PayTradeRebateSearch();
        $dataProvider = $searchModel->makemoneySearch(Yii::$app->request->queryParams);
        return $this->render('makemoney_index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * 详情
     */
    public function actionNview($id){
        $model = PayRebateUsertake::find()
        ->select(['uid','pay_rebate_usertake.id','pay_rebate_usertake.state','tel','take_money','take_time' ,'apply_time','memo'])
        ->join('LEFT JOIN', 'user_info', 'user_info.id = pay_rebate_usertake.uid')
        ->where(['=','pay_rebate_usertake.id',$id])->one();
        return $this->render('nview', [
            'model' => $model,
        ]);
    }
    /**
     * Displays a single PayTradeRebate model.
     * @param integer $uid
     * @param string $trade_no
     * @return mixed
     */
    public function actionView($uid, $trade_no)
    {
        return $this->render('view', [
            'model' => $this->findModel($uid, $trade_no),
        ]);
    }

    /**
     * Creates a new PayTradeRebate model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new PayTradeRebate();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'uid' => $model->uid, 'trade_no' => $model->trade_no]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing PayTradeRebate model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $uid
     * @param string $trade_no
     * @return mixed
     */
    public function actionUpdate($uid, $trade_no)
    {
        $model = $this->findModel($uid, $trade_no);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'uid' => $model->uid, 'trade_no' => $model->trade_no]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing PayTradeRebate model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $uid
     * @param string $trade_no
     * @return mixed
     */
    public function actionDelete($uid, $trade_no)
    {
        $this->findModel($uid, $trade_no)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the PayTradeRebate model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $uid
     * @param string $trade_no
     * @return PayTradeRebate the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($uid, $trade_no)
    {
        if (($model = PayTradeRebate::findOne(['uid' => $uid, 'trade_no' => $trade_no])) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    /**
     * 打款
     */
    public function actionCheckMakemoney(){
        //判断当前用户是否有打款权限
        if(!Yii::$app->user->can('user-rebates-makemoney')){
            throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
        }
        $post=Yii::$app->request->post();
         $idlist=$post['ids'];
        $count=count($idlist);
        $return_result=array("code"=>'1',"msg"=>'打款成功',"pid"=>0);
        if($count>1){
            //多条打款
             for($i=0;$i<$count;$i++){
                    $rebateInfo=PayRebateUsertake::findOne($idlist[$i]);
                    $aliAccount=$rebateInfo['aliAccount'];
                    $wxOpenid=$rebateInfo['wxOpenid'];
                    $take_money=number_format($rebateInfo['take_money']*0.92,2, '.', '');
                    $state=intval($rebateInfo['state']);
                    if($state==1){
                        //判断是否重复打款
                        $sql="SELECT id FROM pay_makemoney_log WHERE p_id=:pid AND state=1";
                        $param=array(":pid"=>$idlist[$i]);
                        $paylog=MakemoneyLog::findBySql($sql,$param)->asArray()->one();
                        if(count($paylog)==0){
                            //进行打款
                            if($aliAccount!=""){
                                $type=1;//支付宝打款
                                $result=$this->actionAlipay($aliAccount, $take_money);
                                $result=json_decode($result);
                                $result=(array)$result;
                                $code=$result['code'];
                                $msg=$result['msg'];
                                if($code=="10000"){//转账成功
                                    $rebateInfo->state=2;
                                    $rebateInfo->give_uid=Yii::$app->user->identity->id;
                                    $rebateInfo->take_time=time();
                                    $rebateInfo->save();
                                    //添加转账记录
                                    $order_id=$result['order_id'];
                                    $pay_date=$result['pay_date'];
                                    $MakemoneyLog=new MakemoneyLog();
                                    $MakemoneyLog['p_id']=$rebateInfo['id'];
                                    $MakemoneyLog['uid']=$rebateInfo['uid'];
                                    $MakemoneyLog['type']=1;
                                    $MakemoneyLog['alipay_order_id']=$order_id;
                                    $MakemoneyLog['pay_date']=strtotime($pay_date);
                                    $MakemoneyLog['wx_partner_trade_no']="";
                                    $MakemoneyLog['wx_payment_no']="";
                                    $MakemoneyLog['createtime']=time();
                                    $MakemoneyLog['state']=1;
                                    $MakemoneyLog['msg']=$msg;
                                    $MakemoneyLog['money']=$take_money;
                                    $MakemoneyLog->save();
                                }else{
                                    //转账失败
                                    $MakemoneyLog=new MakemoneyLog();
                                    $MakemoneyLog['p_id']=$rebateInfo['id'];
                                    $MakemoneyLog['uid']=$rebateInfo['uid'];
                                    $MakemoneyLog['type']=1;
                                    $MakemoneyLog['alipay_order_id']="";
                                    $MakemoneyLog['pay_date']=0;
                                    $MakemoneyLog['wx_partner_trade_no']="";
                                    $MakemoneyLog['wx_payment_no']="";
                                    $MakemoneyLog['createtime']=time();
                                    $MakemoneyLog['state']=2;
                                    $MakemoneyLog['msg']=$msg;
                                    $MakemoneyLog['money']=$take_money;
                                    $MakemoneyLog->save();
                                    $return_result=array("code"=>'2',"msg"=>"支付宝打款失败：".$msg,"pid"=>$rebateInfo['id']);
                                }
                            }else{
                                $type=2;//微信打款
                                $result=$this->actionSettle($wxOpenid, $take_money);
                                $result=json_decode($result);
                                $result=(array)$result;
                                $code=$result['code'];
                                $msg=$result['msg'];
                                if($code=="1"){//转账成功
                                    $rebateInfo->state=2;
                                    $rebateInfo->give_uid=Yii::$app->user->identity->id;
                                    $rebateInfo->take_time=time();
                                    $rebateInfo->save();
                                    //添加转账记录
                                    $partner_trade_no=$result['partner_trade_no'];
                                    $payment_no =$result['payment_no'];
                                    $payment_time =$result['payment_time'];
                                    $MakemoneyLog=new MakemoneyLog();
                                    $MakemoneyLog['p_id']=$rebateInfo['id'];
                                    $MakemoneyLog['uid']=$rebateInfo['uid'];
                                    $MakemoneyLog['type']=2;
                                    $MakemoneyLog['alipay_order_id']="";
                                    $MakemoneyLog['pay_date']=strtotime($payment_time);
                                    $MakemoneyLog['wx_partner_trade_no']=$partner_trade_no;
                                    $MakemoneyLog['wx_payment_no']=$payment_no;
                                    $MakemoneyLog['createtime']=time();
                                    $MakemoneyLog['state']=1;
                                    $MakemoneyLog['msg']=$msg;
                                    $MakemoneyLog['money']=$take_money;
                                    $MakemoneyLog->save();
                                }else{
                                    //转账失败
                                    $MakemoneyLog=new MakemoneyLog();
                                    $MakemoneyLog['p_id']=$rebateInfo['id'];
                                    $MakemoneyLog['uid']=$rebateInfo['uid'];
                                    $MakemoneyLog['type']=2;
                                    $MakemoneyLog['alipay_order_id']="";
                                    $MakemoneyLog['pay_date']=0;
                                    $MakemoneyLog['wx_partner_trade_no']="";
                                    $MakemoneyLog['wx_payment_no']="";
                                    $MakemoneyLog['createtime']=time();
                                    $MakemoneyLog['state']=2;
                                    $MakemoneyLog['msg']=$msg;
                                    $MakemoneyLog['money']=$take_money;
                                    $MakemoneyLog->save();
                                    $return_result=array("code"=>'2',"msg"=>'微信打款失败'.$msg,"pid"=>$rebateInfo['id']);
                                }
                            }//微信打款 结束标签
                        }//判断是否重复打款情况
                        
                    }else{//判断打款状态==1
                        $return_result=array("code"=>'2',"msg"=>$rebateInfo['id'].'存在重复打款,请稍后再试!',"pid"=>$rebateInfo['id']);
                        echo json_encode($return_result);exit();
                    }
                }//for 结束
                
        }else{
           //单条打款  
            $rebateInfo=PayRebateUsertake::findOne($idlist[0]);
            $aliAccount=$rebateInfo['aliAccount'];
            $wxOpenid=$rebateInfo['wxOpenid'];
            $take_money=number_format($rebateInfo['take_money']*0.92,2, '.', '');
            $state=intval($rebateInfo['state']);
            if($wxOpenid==""&&$aliAccount==""){
                $return_result=array("code"=>'2',"msg"=>'用户不存在，打款失败',"pid"=>$rebateInfo['id']);
                echo json_encode($return_result);exit();
            }
            if($state==1){
                $sql="SELECT id FROM log_pay_makemoney WHERE p_id=:pid AND state=1";
                $param=array(":pid"=>$idlist[0]);
                $paylog=MakemoneyLog::findBySql($sql,$param)->asArray()->one();
                if(count($paylog)==0){
                    //进行打款
                    if($aliAccount!=""){
                        $type=1;//支付宝打款
                        $result=$this->actionAlipay($aliAccount, $take_money);
                        $result=json_decode($result);
                        $result=(array)$result;
                        $code=$result['code'];
                        $msg=$result['msg'];
                        if($code=="10000"){//转账成功
                            $rebateInfo->state=2;
                            $rebateInfo->give_uid=Yii::$app->user->identity->id;
                            $rebateInfo->take_time=time();
                            $rebateInfo->save();
                            //添加转账记录
                            $order_id=$result['order_id'];
                            $pay_date=$result['pay_date'];
                            $sign=$result['sign'];
                            $MakemoneyLog=new MakemoneyLog();
                            $MakemoneyLog['p_id']=$rebateInfo['id'];
                            $MakemoneyLog['uid']=$rebateInfo['uid'];
                            $MakemoneyLog['type']=1;
                            $MakemoneyLog['alipay_order_id']=$order_id;
                            $MakemoneyLog['pay_date']=strtotime($pay_date);
                            $MakemoneyLog['wx_partner_trade_no']="";
                            $MakemoneyLog['wx_payment_no']="";
                            $MakemoneyLog['createtime']=time();
                            $MakemoneyLog['state']=1;
                            $MakemoneyLog['msg']=$msg;
                            $MakemoneyLog['money']=$take_money;
                            $MakemoneyLog->save();
                            $return_result=array("code"=>'1',"msg"=>'支付宝打款成功',"pid"=>$rebateInfo['id']);
                        }else{
                            //转账失败  设置状态为打钱中
                            $MakemoneyLog=new MakemoneyLog();
                            $MakemoneyLog['p_id']=$rebateInfo['id'];
                            $MakemoneyLog['uid']=$rebateInfo['uid'];
                            $MakemoneyLog['type']=1;
                            $MakemoneyLog['alipay_order_id']="";
                            $MakemoneyLog['pay_date']=0;
                            $MakemoneyLog['wx_partner_trade_no']="";
                            $MakemoneyLog['wx_payment_no']="";
                            $MakemoneyLog['createtime']=time();
                            $MakemoneyLog['state']=2;
                            $MakemoneyLog['msg']=$msg;
                            $MakemoneyLog['money']=$take_money;
                            $MakemoneyLog->save();
                            $return_result=array("code"=>'2',"msg"=>'支付宝打款失败:'.$msg,"pid"=>$rebateInfo['id']);
                        }
                    }else{
                        $type=2;//微信打款
                        $result=$this->actionSettle($wxOpenid, $take_money);
                        $result=json_decode($result);
                        $result=(array)$result;
                        $code=$result['code'];
                        $msg=$result['msg'];
                        if($code=="1"){//转账成功
                            $rebateInfo->state=2;
                            $rebateInfo->give_uid=Yii::$app->user->identity->id;
                            $rebateInfo->take_time=time();
                            $rebateInfo->save();
                            //添加转账记录
                            $partner_trade_no=$result['partner_trade_no'];
                            $payment_no =$result['payment_no'];
                            $payment_time =$result['payment_time'];
                            $MakemoneyLog=new MakemoneyLog();
                            $MakemoneyLog['p_id']=$rebateInfo['id'];
                            $MakemoneyLog['uid']=$rebateInfo['uid'];
                            $MakemoneyLog['type']=2;
                            $MakemoneyLog['alipay_order_id']="";
                            $MakemoneyLog['pay_date']=strtotime($payment_time);
                            $MakemoneyLog['wx_partner_trade_no']=$partner_trade_no;
                            $MakemoneyLog['wx_payment_no']=$payment_no;
                            $MakemoneyLog['createtime']=time();
                            $MakemoneyLog['state']=1;
                            $MakemoneyLog['msg']=$msg;
                            $MakemoneyLog['money']=$take_money;
                            $MakemoneyLog->save();
                            $return_result=array("code"=>'1',"msg"=>'微信打款成功',"pid"=>$rebateInfo['id']);
                        }else{
                            //转账失败  设置状态为打钱中
                            $MakemoneyLog=new MakemoneyLog();
                            $MakemoneyLog['p_id']=$rebateInfo['id'];
                            $MakemoneyLog['uid']=$rebateInfo['uid'];
                            $MakemoneyLog['type']=2;
                            $MakemoneyLog['alipay_order_id']="";
                            $MakemoneyLog['pay_date']=0;
                            $MakemoneyLog['wx_partner_trade_no']="";
                            $MakemoneyLog['wx_payment_no']="";
                            $MakemoneyLog['createtime']=time();
                            $MakemoneyLog['state']=2;
                            $MakemoneyLog['msg']=$msg;
                            $MakemoneyLog['money']=$take_money;
                            $MakemoneyLog->save();
                            $return_result=array("code"=>'2',"msg"=>'微信打款失败:'.$msg,"pid"=>$rebateInfo['id']);
                        }
                    }//微信打款 结束标签
                }else{
                    $return_result=array("code"=>'2',"msg"=>$rebateInfo['id'].'存在重复打款',"pid"=>$rebateInfo['id']);
                }
                
            }//判断打款状态！=2 结束标签
        }//单条打款  结束标签
        echo json_encode($return_result,true);exit();
    }
    protected function actionAlipay( $payee_account, $account){
      /*    $payee_account="15067161882";
        $account=0.01;   */
        if($payee_account==""){
            $response_result=array("code"=>2222,"msg"=>"支付宝账号为空！","order_id"=>"无","pay_date"=>"无","sign"=>"无");
            return json_encode($response_result); 
        }elseif(doubleval($account)<0.1){
            $response_result=array("code"=>3333,"msg"=>"单笔金额不可小于0.1元！","order_id"=>"无","pay_date"=>"无","sign"=>"无");
            return json_encode($response_result);
        }   
        $tm = date('Ymdhis');
        $at = intval(rand(0,999999));
        $config['appId']=Yii::$app->params['alipay']['appid'];
        $config['rsaPrivateKey']=Yii::$app->params['alipay']['rsaPrivateKey'];
        $config['alipayrsaPublicKey']=Yii::$app->params['alipay']['alipayrsaPublicKey'];
        $param['out_biz_no']= $tm.$at;
        $param['payee_account']=$payee_account;//收款方账户
        $param['account']=$account;//转账金额 必须大于等于0.1元
        $param['payer_show_name']=Yii::$app->params['siteCompany'];//付款方姓名
        $param['remark']="提现";//转账备注
        $makemoneyApi=new  makemoneyApi();
        $responseObj= makemoneyApi::makemoney($config, $param);
        $responseArray=json_decode($responseObj);
        $responseArray=(array)$responseArray;
        return  json_encode($responseArray);
    }
    /**
     * 微信企业接口转账
     * @param   $openid
     * @param  $amount
     * @return string
     */
    public function actionSettle($openid,$amount) {//
       /*  $openid="of7IXt9zB3HfNmP7IDTc9Akw53ss";
        $amount=0.1; */
         if (doubleval($amount) >20000) {//单笔2万交易额 
            return json_encode(array("code"=>4,"msg"=>"单笔提现2万元，以防有诈！终止提现"));
        }elseif(doubleval($amount)<1){
            return json_encode(array("code"=>3,"msg"=>"提现不能少于1元"));
        }
        $amount = doubleval($amount)* 100;//单位  分
        if (doubleval($amount) <100) {
            return json_encode(array("code"=>3,"msg"=>"提现不能少于1元")); 
        }  
        $package['mch_appid'] = Yii::$app->params['weixin']['WX_APPID'];
        $package['mchid'] =  Yii::$app->params['weixin']['WX_MCHID'];
        $package['nonce_str'] =  PayRebateUsertake::getRandChar(15);
        $package['check_name'] = 'NO_CHECK';
        $package['partner_trade_no'] = Yii::$app->params['weixin']['WX_MCHID'].date("YmdHis");
        $package['openid'] = $openid;
        $package['re_user_name'] = "";//收款用户姓名 可选
        $package['amount'] = $amount;
        $package['desc'] = '过夹夹设计师提现';
        $package['spbill_create_ip'] =Yii::$app->request->userIP;
        $package =PayRebateUsertake::secretkeyAction($package);
        $dat = PayRebateUsertake::array2xml($package);
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
        $responseXml = PayRebateUsertake::curl_post_ssl($url, $dat);
        $responseObj = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $responseArr = (array)$responseObj;
        //企业支付出错
        if ($responseArr['result_code'] == 'FAIL') {
            $payresult= json_encode(array("code"=>2,"msg"=>$responseArr['return_msg'],
                "partner_trade_no"=>"无",
                "payment_no"=>"无",
                "payment_time"=>"无"
            ));
        }elseif($responseArr['result_code'] == 'SUCCESS'){
            $payresult=json_encode(array("code"=>1,"msg"=>"支付成功",
                "partner_trade_no"=>$responseArr['partner_trade_no'],
                "payment_no"=>$responseArr['payment_no'],
                "payment_time"=>$responseArr['payment_time']
            )); 
        }
         return $payresult;
    }
   
}
